﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Galaktika.BI.Runtime.Services;
using Ranet.AgOlap.Controls.MemberChoice.ClientServer;
using Galaktika.BI.Silverlight.Commands;
using System.Threading;
using Ranet.AgOlap.Controls.General;
using Galaktika.BI.Silverlight.Services;
using Ranet.Olap.Core;
//using Ranet.Olap.Core.Compressor;

namespace Galaktika.BI.Silverlight.Controls.General
{
    public class MembersDataLoaderEx : IDataLoader
    {
        UserControl Owner = null;
        public MembersDataLoaderEx(UserControl owner)
            : base()
        {
            Owner = owner;
        }

        public IBindingContext Context { get; set; }

        #region IDataLoader Members

        public void LoadData(object schema, object state)
        {
            MemberChoiceQuery args = XmlUtility.XmlStr2Obj<MemberChoiceQuery>(schema.ToString());
            if (args != null)
            {
                IUserTaskManager taskManager = (IUserTaskManager)Context.Services.GetService(typeof(IUserTaskManager));
                if (taskManager != null)
                {
                    InvokeSchema invokeSchema = null;
                    String taskText = String.Empty;
                    invokeSchema = CommandBuilder.CreateMemberChoiceQuerySchema((string)this.Context.UserData["_$Id"], args.Connection, args);
                    switch(args.QueryType)
                    {
                        case  MemberChoiceQueryType.FindMembers:
                            taskText = Localization.AppTask_FindingMembers;
                            break;
                        case MemberChoiceQueryType.GetAscendants:
                            taskText = String.Format(Localization.AppTask_DownloadingAscendants, args.MemberUniqueName);
                            break;
                        case MemberChoiceQueryType.GetChildrenMembers:
                            taskText = String.Format(Localization.AppTask_DownloadingChildrenMembersFor, args.MemberUniqueName);
                            break;
                        case MemberChoiceQueryType.GetRootMembers:
                            taskText = Localization.AppTask_DownloadingDimension;
                            break;
                        case MemberChoiceQueryType.GetRootMembersCount:
                            taskText = Localization.AppTask_CalcRootMembersCount;
                            break;
                        case MemberChoiceQueryType.GetMember:
                            taskText = String.Format(Localization.AppTask_DownloadingMemberProperties, args.MemberUniqueName);
                            break;
                        case MemberChoiceQueryType.GetMembers:
                            taskText = Localization.AppTask_DownloadingMembers;
                            break;
                        case MemberChoiceQueryType.LoadSetWithAscendants:
                            taskText = Localization.AppTask_DownloadingSelectedMembers;
                            break;
                        default:
                            break;
                    }

                    ChoiceControlInvokeSchemaWrapper wrapper = new ChoiceControlInvokeSchemaWrapper(invokeSchema, state);
                    //taskManager.ProcessTaskItem(taskText,
                    //    new WaitCallback(param => 
                    //        { ThreadPool.QueueUserWorkItem(new WaitCallback(InvokeCommand), param); }
                    //    ), wrapper);
                    taskManager.RunTaskAsync(
                        taskText,
                        param => this.InvokeCommand(param),
                        wrapper);
                }
            }
        }

        public event EventHandler<DataLoaderEventArgs> DataLoaded;

        #endregion

        void Raise_DataLoaded(DataLoaderEventArgs args)
        {
            EventHandler<DataLoaderEventArgs> handler = this.DataLoaded;
            if (handler != null)
            {
                if (Owner != null)
                {
                    Owner.Dispatcher.BeginInvoke(delegate { handler(this, args); });
                }
                else 
                {
                    handler(this, args); 
                }
            }
        }

        void InvokeCommand(object state)
        {
            ChoiceControlInvokeSchemaWrapper wrapper = state as ChoiceControlInvokeSchemaWrapper;
            if (wrapper != null)
            {
                InvokeSchema schema = wrapper.Schema;
                using (var cmd = CommandDispatcher.Dispatch(schema))
                {
                    InvokeResultSchema res = cmd.Invoke();

                    String content = res.Content;
#warning Отключена zip-архивация
                    //if (res.IsArchive)
                    //{
                    //    content = ZipCompressor.DecompressFromBase64String(res.Content);
                    //}

                    InvokeResultDescriptor result = new InvokeResultDescriptor(content);
                    if (res.ContentType == KnownContentTypes.ADOMDError ||
                        res.ContentType == KnownContentTypes.Error)
                        result.ContentType = InvokeContentType.Error;


                    Raise_DataLoaded(new DataLoaderEventArgs(result, null, wrapper.UserState));
                }
            }
        }
    }
}
